<template>
  <el-popover
    placement="bottom"
    width="200"
    trigger="click"
    @show="handleCustomShow"
    @hide="handleCustomHide"
  >
    <el-button
      slot="reference"
      size="small"
    >自定义字段</el-button>
    <el-checkbox-group
      @click.stop
      v-model="checked"
      @change="handleChange"
    >
      <el-checkbox
        class="u-lh32"
        v-for="item in customColumn"
        :key="item.key"
        :label="item.value"
      >{{item.label}}</el-checkbox>
    </el-checkbox-group>
  </el-popover>
</template>

<script>
import { sessionStorage } from "@/utils";
import { fetchCustomUpdate, fetchCustom } from "@/api";
export default {
  name: "CustomTableColumn",
  props: {
    module: {
      type: Number,
      default: 0
    },
    columns: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      user: sessionStorage.get("USER"),
      isEnterAccount: sessionStorage.get("ENTER_USER_NAME") ? 1 : 0,
      propColumn: this.columns,
      beforeChecked: [],
      checked: []
    };
  },
  computed: {
    customColumn() {
      return this.propColumn
        .filter(item => item.custom)
        .map(item => {
          return {
            value: item.prop,
            label: item.label
          };
        });
    }
  },
  methods: {
    // 保存/更新自定义
    fetchCustomUpdate(field) {
      fetchCustomUpdate({
        body: {
          customField: field,
          isEnterInto: this.isEnterAccount,
          module: this.module,
          userId: this.user.userId
        }
      }).then(() => {
        this.$message.info("更新自定义字段");
      });
    },
    // 获取自定义
    fetchCustom() {
      fetchCustom({
        body: {
          isEnterInto: this.isEnterAccount,
          module: this.module,
          userId: this.user.userId
        }
      }).then(res => {
        if (res.data && res.data.customField) {
          this.checked = res.data.customField.split(",");
          this.propColumn.forEach(column => {
            if (this.checked.includes(column.prop)) {
              column.visible = true;
            }
          });
          this.$emit("update:columns", this.propColumn);
        }
      });
    },
    handleChange() {
      let custom = this.propColumn.filter(item => item.custom);
      // 更新列表
      custom.forEach(item => {
        item.visible = this.checked.includes(item.prop);
      });
      this.$emit("update:columns", this.propColumn);
    },
    handleCustomShow() {
      this.beforeChecked = this.propColumn
        .filter(item => item.custom && item.visible)
        .map(item => item.prop);
    },
    handleCustomHide() {
      // 更新自定义
      let checked = this.propColumn
        .filter(item => item.custom && item.visible)
        .map(item => item.prop);
      if (this.module && this.beforeChecked.join() !== checked.join()) {
        this.fetchCustomUpdate(checked.join());
      }
    }
  },
  created() {
    this.fetchCustom();
  }
};
</script>